import { Effect, Reducer, Subscription, history } from 'umi';
import { login } from '@/api/login';
import { getToken, setToken, removeToken } from '@/utils/auth';
import Cookies from 'js-cookie';
import { notification } from 'antd';
interface LoginModelType {
  namespace: 'logins';
  state: {};
  effects: {
    updateLoginForm: Effect;
    logout: Effect;
  };
  reducers: {
    saveLoginForm: Reducer;
    changeLoginStatus: Reducer;
    saveGetcookie: Reducer;
    saveChangeRememberMe: Reducer;
    saveUuid: Reducer;
    savelogout: Reducer;
  };
}
const LoginModel: LoginModelType = {
  namespace: 'logins',
  state: {
    username: 'admin',
    password: 'admin123',
    code: '',
    uuid: '',
    rememberMe: false,
    token: getToken(),
  },
  reducers: {
    saveLoginForm(state, { payload }) {
      return {
        ...state,
        password: payload.password,
        username: payload.username,
        code: payload.code,
        uuid: payload.uuid,
      };
    },
    changeLoginStatus(state, { payload }) {},
    saveGetcookie(state, action) {
      const username = Cookies.get('username');
      const password = Cookies.get('password');
      const rememberMe = Cookies.get('rememberMe');
      return {
        ...state,
        username: username,
        passwrod: password,
        rememberMe: rememberMe,
      };
    },
    saveChangeRememberMe(state, { payload }) {
      return {
        ...state,
        rememberMe: payload,
      };
    },
    saveUuid(state, { payload }) {
      return {
        ...state,
        uuid: payload,
      };
    },
    savelogout(state, { call,put }) {
      removeToken();
      history.push('/login')
      return {
        ...state,
      };
    },
  },
  effects: {
    *updateLoginForm({ payload }, { call, put }) {
      const res = yield call(login, { payload });
      yield put({
        type: 'saveLoginForm',
        payload: payload,
      });
      if (res.code == 200) {
        //登录状态处理
        setToken(res.token);
        history.push('/');
      } else {
        notification['error']({
          message: '验证码错误',
          description: res.msg,
          onClick: () => {
            console.log('关闭此对话框');
          },
        });
      }
    },
    *logout(_, { put }) {
      yield put({
        type: 'savelogout',
      });
    },
  },
};
export default LoginModel;
